import axios from "axios";
import { AxiosRequestConfigExpand, AxiosResponseExpand } from "@/types/axios.d.ts";
import { MAINHOST } from "@/axios/config";
import { getToken } from "@/utils/common";
import store from "@/store/index";
import message from "ant-design-vue/es/message";
import router from "@/router";

const instance = axios.create();
const state: any = store.state;

const token = getToken();

// 请求拦截
instance.interceptors.request.use(
  (config: AxiosRequestConfigExpand) => {
    token && (config.headers.Authorization = token);
    
    // 显示全局的loading...
    config.loading = config.loading === undefined ? true : config.loading;
    store.dispatch('setSpinLoading', config.loading );

    if(!state.app.resetBaseUrl) {
      //默认请求地址
      config.baseURL = MAINHOST;
    }

    //请求超时时间
    config.timeout = config.timeout || 10000;

    //请求头
    config.headers['Content-Type'] = 'application/json, text/plain';

    return config;
  },
  error => {
    return Promise.reject(error)
  }
);
// 响应拦截
instance.interceptors.response.use(
  (res: AxiosResponseExpand) => {
    store.dispatch('setSpinLoading', false);
    const { data, status } = res;
    return Promise.reject(data);
  },
  (error: any) => {
    store.dispatch('setSpinLoading', false);
    switch (error && error.response && error.response.status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        error.message = '未授权，请登录';
        router.replace({ name: "login" });
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = '未找到访问地址'
        break
      case 406:
        error.message = "请求的资源并不符合要求。";
        break;
      case 408:
        error.message = '请求超时';
        break
      case 413:
        error.message = "请求体过大。";
        break;
      case 415:
        error.message = "类型不正确。";
        break;
      case 416:
        error.message = "请求的区间无效。";
        break;
      case 500:
        error.message = '服务器内部错误'
        break
      case 501:
        error.message = '服务未实现'
        break
      case 502:
        error.message = '网关错误'
        break
      case 503:
        error.message = '服务不可用'
        break
      case 504:
        error.message = '网关超时'
        break
      case 505:
        error.message = 'HTTP版本不受支持'
        break
      default:
    }
    message.error(error.message || error, 1);

    return Promise.reject(error);
  }
);

export default instance;
